package com.letv.ads.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.letv.adlib.sdk.types.AdElementMime;
import com.letv.ads.AdsManager;
import com.letv.android.sdk.R;
import com.letv.ads.util.AdJSBridge;
import com.letv.ads.util.ApkDownloadAsyncTask;
import com.letv.ads.util.ISensorCallback;
import com.letv.ads.util.LogInfo;

import java.lang.reflect.Method;

public class LetvWebViewActivity extends Activity implements OnClickListener {
    private static final String TAG = "LetvWebViewActivity";
    private WebView mWebView;

    private String baseUrl;

    private ImageView refresh;

    private ProgressBar progressBar;

    private boolean isFinish;

    private ImageView close;

    private TextView titleView;
    private TextView urlTitleView;

    private String loadType;

    private AdJSBridge jsBridge;

    private ISensorCallback iSensorCallback;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case AdJSBridge.CLOSE_WEBVIEW:
                LetvWebViewActivity.this.finish();
                break;
            case AdJSBridge.REFRESH_WEBVIEW:
                mWebView.reload();
                break;
            case AdJSBridge.FULLSCREEN_WEBVIEW:
                getWindow().setFlags(
                        WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case AdJSBridge.RESTORE_SIZE_WEBVIEW:
                final WindowManager.LayoutParams attrs = getWindow()
                        .getAttributes();
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().setAttributes(attrs);
                getWindow().clearFlags(
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                break;
            }
            super.handleMessage(msg);
        }
    };

    public static void launch(Context context, String url, String title) {
        Intent intent = new Intent(context, LetvWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("loadType", title);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void launch(Context context, String url, String title, AdElementMime adElem) {
        // url = "http://minisite.letv.com/thirdparty/mtestone/index.shtml";
        Intent intent = new Intent(context, LetvWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("loadType", title);
        intent.putExtra("adInfo", adElem);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.letv_ad_webview);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        Intent intent = getIntent();
        loadType = intent.getStringExtra("loadType");
        baseUrl = intent.getStringExtra("url");
        LogInfo.log(TAG, "onCreate baseUrl=" + baseUrl);

        jsBridge = new AdJSBridge((AdElementMime) intent.getParcelableExtra("adInfo"));

        findView();
    }

    private void findView() {
        refresh = (ImageView) findViewById(R.id.refresh);
        progressBar = (ProgressBar) findViewById(R.id.loading_progress);
        titleView = (TextView) findViewById(R.id.letv_webview_title);
        urlTitleView = (TextView) findViewById(R.id.webview_title_url);
        close = (ImageView) findViewById(R.id.close_iv);

        ImageView back_iv = (ImageView) findViewById(R.id.back_iv);
        back_iv.setOnClickListener(this);
        mWebView = (WebView) findViewById(R.id.webView);
        if (null != AdsManager.getInstance().iAdJSBridge) {
            AdsManager.getInstance().iAdJSBridge.setJSBridge(this, mWebView, mHandler, null);
        }
        jsBridge.setJSBridge(this, mWebView, mHandler, null);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.setHorizontalScrollBarEnabled(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new LetvWebViewClient());
        mWebView.setWebChromeClient(new LetvWebViewChromeClient());

        try {
            if (!TextUtils.isEmpty(baseUrl)
                    && !baseUrl.contains("ark.letv.com")
                    && !baseUrl.contains("ref=")
                    && baseUrl.contains("letv.com")) {
                if (baseUrl.contains("?")) {
                    baseUrl += "&ref=0101";
                } else {
                    baseUrl += "?ref=0101";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        mWebView.loadUrl(baseUrl);

        if (baseUrl != null) {
            String url = baseUrl;
            if (baseUrl.length() > 0) { // baseUrl的格式：http://m.letv.com/2014/
                if (url.contains("http://")) {
                    if (url.contains("to=http%3A%2F%2F")) {
                        url = url
                                .substring(url.indexOf("to=http%3A%2F%2F") + 16);
                        if (url.contains("%2F")) {
                            url = url.substring(0, url.indexOf("%2F"));
                        }
                    } else {
                        url = url.replace("http://", "");
                        if (url.contains("/")) {
                            int end = url.indexOf("/");
                            url = (String) url.subSequence(0, end);
                        }
                    }
                }
            }
            urlTitleView.setText("由  " + url + " 提供");
        }
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent,
                    String contentDisposition, String mimetype,
                    long contentLength) {
                if (url.endsWith(".apk")) {
                    ApkDownloadAsyncTask.downloadApk(LetvWebViewActivity.this,
                            url, loadType);
                    finish();
                } else {
                    Toast.makeText(LetvWebViewActivity.this,
                            R.string.download_failed, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        refresh.setOnClickListener(this);
        close.setOnClickListener(this);
        titleView.setText(loadType);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.close_iv) {
            finish();
        } else if (v.getId() == R.id.back_iv) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
                if (!close.isShown()) {
                    close.setVisibility(View.VISIBLE);
                }
            } else {
                finish();
            }
        } else if (v.getId() == R.id.refresh) {
            mWebView.reload();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            isFinish = true;
            if (mWebView != null) {
                mWebView.stopLoading();
                /**
                 * 3.0以上系统编译，如果不隐藏webview会出现崩溃
                 */
                mWebView.setVisibility(View.GONE);
                mWebView.destroy();
            }
            if (jsBridge != null) {
                jsBridge.onDestory();
            }
            // mSensorManager.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        callHiddenWebViewMethod("onPause");
        if (jsBridge != null) {
            jsBridge.onWebviewHide();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        callHiddenWebViewMethod("onResume");
        if (jsBridge != null) {
            jsBridge.onWebviewShow();
        }
    }

    private void callHiddenWebViewMethod(String name) {
        if (mWebView != null) {
            try {
                Method method = WebView.class.getMethod(name);
                method.invoke(mWebView);
            } catch (Exception e) {
            }
        }
    }

    private class LetvWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                int index = url.indexOf("?");
                if (index > 0) {
                    String u = url.substring(0, url.indexOf("?"));
                    if (".mp4"
                            .equals(u.substring(u.lastIndexOf(""), u.length()))
                            && url.contains("vtype=mp4")) {
                        view.stopLoading();
                        if (!isFinish) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            String type = "video/mp4";
                            Uri name = Uri.parse(url);
                            intent.setDataAndType(name, type);
                            intent.putExtra(
                                    MediaStore.EXTRA_SCREEN_ORIENTATION,
                                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                            LetvWebViewActivity.this.startActivity(intent);
                        }
                        return true;
                    } else {
                        view.loadUrl(url);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    private class LetvWebViewChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (progressBar.getVisibility() != View.VISIBLE) {
                progressBar.setVisibility(View.VISIBLE);
                urlTitleView.setVisibility(View.VISIBLE);
            }
            progressBar.setProgress(newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
                urlTitleView.setVisibility(View.GONE);
            }
        }
    }
}
